﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
using System.Drawing;
namespace DataProcess {
	public partial class frmWordReplace : Form {
		private WebBrowser browser = new WebBrowser();
		public frmWordReplace() {
			InitializeComponent();
			Debug.Listeners.Add(new ListBoxTraceListener(listBox1));
		}

		private void button1_Click(object sender, EventArgs e) {
			Debug.WriteLine("开始时间：{0}", DateTime.Now);
			word_resource_mapDataSetTableAdapters.resourceTableAdapter adp = new word_resource_mapDataSetTableAdapters.resourceTableAdapter();
			var table = adp.GetData();
			object True = true, False = false;
			object collEnd = WdCollapseDirection.wdCollapseEnd,
				collStart = WdCollapseDirection.wdCollapseStart,
				unitPh = WdUnits.wdParagraph,
				count1 = 1;
			Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
			app.Visible = true;
			Document doc = null;
			object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
			string snapshot = "snapshot.png";
			string queryName = "graphicId=";

			//分组
			var group = table.GroupBy(row => row.字段4);
			foreach (IGrouping<string, word_resource_mapDataSet.resourceRow> item in group) {
				//if (!item.Key.Contains("1613")) {
				//    continue;
				//}
				object fileName = Path.Combine(System.Windows.Forms.Application.StartupPath, "30个topic", item.Key.Substring(item.Key.IndexOf("/") + 1) + ".docx");
				doc = app.Documents.Open(fileName);
				doc.TrackRevisions = false;
				doc.Activate();
				List<string> processed = new List<string>();
				Dictionary<int, List<Keyword>> needInsert = new Dictionary<int, List<Keyword>>();
				try {
					foreach (word_resource_mapDataSet.resourceRow keywordRow in item) {
						string keyword = keywordRow.字段1;

						string gId = keywordRow.字段3;
						gId = gId.Substring(gId.IndexOf('/') + 1);
						string resourceDir = Path.Combine(System.Windows.Forms.Application.StartupPath, "表格和图片");
						if (!Directory.Exists(Path.Combine(resourceDir, gId))) {
							Debug.WriteLine("未能找到关键字路径:{0}|{1}|{2}", item.Key, keyword, gId);
							continue;
						}
						bool finded = false;
						#region 查找并插入对应的关键字
						foreach (Hyperlink link in doc.Hyperlinks) {
							string hText = link.Range.Text;
							if (!hText.Contains(keyword)) {
								continue;
							}
							finded = true;
							string[] gIds = link.Address.Substring(link.Address.LastIndexOf(queryName) + queryName.Length).Split('|');


							string[] gText = getKeyArray(hText);

							if (gText.Length > 1) {
								for (int h = 1; h < gText.Length; h++) {
									gText[h] = gText[0].Remove(gText[0].Length - gText[h].Length) + gText[h];
								}
							}
							if (link.Address.IndexOf(queryName) == -1 || !gText.Contains(keyword)) {
								continue;
							}
							#region 插入内容
							if (gIds.Length != gText.Length) {
								Debug.WriteLine("找到的关键字和ID不完全对应:{0}|{1}|{2}", item.Key, keyword, gId);
								break;
							}
							if (link.Range.ListParagraphs.Count > 0) {
								link.Range.ListParagraphs[1].Range.Select();
								//Debug.WriteLine("List:{0}|{1}", item.Key, keyword);
								int moved = 1;
								while (app.Selection.Range.ListParagraphs.Count > 0 && moved > 0) {
									moved = app.Selection.MoveDown(unitPh, count1);
								}
								app.Selection.Collapse(collStart);
							}
							else if (link.Range.Paragraphs.Count > 0) {
								link.Range.Paragraphs[1].Range.Select();
								app.Selection.Collapse(collEnd);
								//Debug.WriteLine("Paragraphs:{0}|{1}", item.Key, keyword);
							}
							else {
								Debug.WriteLine("未找到段落:{0}|{1}", item.Key, keyword);
							}
							var rangPosition = app.Selection.Range.End;
							if (!needInsert.ContainsKey(rangPosition)) {
								needInsert.Add(rangPosition, new List<Keyword>());
							}
							for (int k = 0; k < gIds.Length; k++) {
								if (processed.Contains(gText[k])) {
									continue;
								}
								processed.Add(gText[k]);

								//Debug.WriteLine(string.Format("keyword:{0};text:{1};id:{2}", keyword, hText, graphicId[k]));
								var select = item.Where(row => row.字段1 == gText[k]).ToArray();
								//var select = item.Select(string.Format("字段1='{0}' and 字段4='{1}'", gText[k], articleIndex));
								if (select.Length > 0) {
									gIds[k] = select[0].字段3;
									gIds[k] = gIds[k].Substring(gIds[k].IndexOf('/') + 1);
								}
								string snapshotPath = Path.Combine(resourceDir, gIds[k], snapshot);
								if (!File.Exists(snapshotPath)) {
									Debug.WriteLine("未能找到快照文件:{0}|{1}", item.Key, snapshotPath);
								}
								needInsert[rangPosition].Add(new Keyword { Key = gText[k], Id = gIds[k], File = snapshotPath });


								//Debug.WriteLine(app.Selection.Range.Text);
								//phr.Range.InsertParagraph();
								//app.Selection.Range.Text = gText[k]; 

							}
							#endregion
						}

						#endregion

						if (!finded && !processed.Contains(keyword)) {
							Debug.WriteLine("在内容里面未能找到关键字:{0}|{1}|{2}", item.Key, keyword, gId);
						}
					}

					foreach (var rang in needInsert.OrderByDescending(pRang => pRang.Key)) {
						app.Selection.SetRange(rang.Key, rang.Key);
						rang.Value.Sort((a, b) => string.Compare(a.Key, b.Key));
						foreach (var key in rang.Value) {
							app.Selection.Collapse(collEnd);
							app.Selection.InsertParagraphAfter();
							app.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
							app.Selection.Range.InlineShapes.AddPicture(key.File);
							app.Selection.InsertAfter(key.Key + Environment.NewLine + Environment.NewLine);
							app.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
						}
					}
				}
				catch (Exception) {
					MessageBox.Show("发生错误！");
					break;
				}
				doc.Close(True);
				doc = null;
			}
			app.Quit(False);
			Debug.WriteLine("结束时间：{0}", DateTime.Now);
			MessageBox.Show("完成！");
		}

		private void button4_Click(object sender, EventArgs e) {
			object miss = System.Reflection.Missing.Value;
			Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
			Document doc = app.Documents.Add(ref miss, ref miss, ref miss, ref miss);
			doc.Activate();
			Table table = doc.Tables.Add(app.Selection.Range, 3, 3, ref miss, ref miss);
			Debug.WriteLine(string.Format("PreferredWidthType:{0}", table.Uniform));
			Debug.WriteLine(string.Format("AutoFormatType:{0}", table.AutoFormatType));

			object save = false;
			doc.Close(ref save, ref miss, ref miss);
			app.Quit(ref save, ref miss, ref miss);
		}

		/// <summary>
		/// 根据找到的文字内容，拆分为关键字数组
		/// </summary>
		/// <param name="hText"></param>
		/// <returns></returns>
		private string[] getKeyArray(string hText) {
			string[] gText = hText.Split(',', '-');
			if (hText.IndexOf('-') > -1 && gText.Last().Length == 1) {
				List<string> gList = new List<string>();
				int lastCode = (int)gText.Last().Last();
				int startCode = (int)gText.First().Last();
				for (int l = startCode; l <= lastCode; l++) {
					gList.Add(((char)l).ToString());
				}
				gList[0] = gText[0];
				gText = gList.ToArray();
			}
			return gText;
		}

		private static void ProcessParagraphs(ref object miss, Microsoft.Office.Interop.Word.Application app, Document doc, ref object replaceAll, string keyword, string snapshot, string type) {
			for (int j = 1; j <= doc.Paragraphs.Count; j++) {
				Find find = doc.Paragraphs[j].Range.Find;
				find.ClearFormatting();
				find.Text = keyword;
				//doc.Paragraphs[j].Range.Select();
				bool finded = find.Execute(
				ref miss, ref miss, ref miss, ref miss, ref miss,
				ref miss, ref miss, ref miss, ref miss, ref miss,
				ref replaceAll, ref miss, ref miss, ref miss, ref miss);
				if (finded) {
					doc.Paragraphs[j].Range.Select();
					//Debug.WriteLine(app.Selection.Range.Start);
					//Debug.WriteLine(app.Selection.Range.End);
					object coll = WdCollapseDirection.wdCollapseEnd;
					app.Selection.Collapse(ref coll);
					app.Selection.InsertParagraphAfter();
					//
					if (type == "Image") {
						var pic = doc.Paragraphs[j + 1].Range.InlineShapes.AddPicture(snapshot, ref miss, ref miss, ref miss);
						pic.Range.Select();
					}
					/*
					if (type == "Table") {
						browser.Url = new Uri(Path.Combine(resourceDir, contentFile));
						while (browser.ReadyState != WebBrowserReadyState.Complete) {
							System.Windows.Forms.Application.DoEvents();
						}
						app.Selection.Range.Paste();
						doc.Paragraphs[j + 1].Range.Select();

						//Table wordTable = doc.Tables.Add(app.Selection.Range, 2, 2, ref miss, ref miss);
						//Debug.WriteLine(string.Format("tablesCount:{0}", app.Selection.Range.Tables.Count));
						Table wordTable = app.Selection.Range.Tables[1];
						//wordTable.Borders[WdBorderType.wdBorderTop].LineStyle = WdLineStyle.wdLineStyleSingle;
						//wordTable.Borders[WdBorderType.wdBorderLeft].LineStyle = WdLineStyle.wdLineStyleSingle;
						//wordTable.Borders[WdBorderType.wdBorderRight].LineStyle = WdLineStyle.wdLineStyleSingle;
						//wordTable.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleSingle;
						//wordTable.Borders[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleSingle;
						//wordTable.Borders[WdBorderType.wdBorderVertical].LineStyle = WdLineStyle.wdLineStyleSingle;

						//Debug.WriteLine(string.Format("AutoFormatType :{0}", wordTable.AutoFormatType));
						//Debug.WriteLine(string.Format("AllowOverlap:{0}", wordTable.Rows.AllowOverlap));
						wordTable.Rows.Alignment = WdRowAlignment.wdAlignRowCenter;
						wordTable.Range.Select();
						//app.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
						//wordTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
					}
					*/
					app.Selection.Collapse(ref coll);
					app.Selection.InsertAfter("\r\n" + keyword + "\r\n");
					app.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
					break;
				}
			}
		}
	}
}
